#-*- coding: utf-8 -*-

import memcache
from sphinxapi import *
from ttserver import *

def parse_item(line):
    pieces = line.split(' ||| ')
    if len(pieces) != 2:
        return []
   
    oquery = pieces[0].strip()
    pieces = pieces[1].split('\t')
    if len(pieces) != 2:
        return []

    query = pieces[0].strip()
    #freq = int(pieces[1].strip())
    freq = pieces[1].strip()
    
    return [oquery, query, freq]

def search_sessiondata(queryexp, oquery="", query="", debug=0):
    ttservers = ['localhost']
    ttports = [11211]

    r = {'result':0, 'matches':[], 'queryexp': '', 'rnum': 0}
	
    for server in ttservers:
        for port in ttports:
            r['rnum'] += int(ttserver_stat(server, port))

    q = ''
    if queryexp:
        q = queryexp
    else:
        if oquery:
            q += '@oquery %s ' % oquery
        if query:
            q += '@query %s' % query

    if not q:
        return r
    
    r['queryexp'] = q

    cl = SphinxClient()
    cl.SetServer ('localhost', 9312)
    cl.SetConnectTimeout(300.0)
    cl.SetMatchMode(SPH_MATCH_EXTENDED)
    cl.SetRankingMode(SPH_RANK_SPH04)
    cl.SetSortMode(SPH_SORT_EXTENDED, 'freq DESC, @rank DESC');

    cl.SetLimits(0, 1000, 1000)

    #print q

    result = cl.Query ( q, 'idx0' )
    if not result:
        print 'query failed: %s' % cl.GetLastError()
        cl.Close()
        return r

    if cl.GetLastWarning():
        print 'WARNING: %s\n' % cl.GetLastWarning()
    
    #if debug > 1:
        #print result

    
    mcservers = {}
    for match in result['matches']:
        #hostid = (match['id'] >> 32) % 3
        #portid =  ((match['id'] >> 32) % 12) / 3

        #host = ttservers[hostid]
        #port = ttports[portid]
        host = 'localhost'
        port = 11211

        address = '%s:%s'  % (host, port)
        #print 'http://%s/%s' % (address, match['id'])
        #continue
        if address not in mcservers:
            mc = memcache.Client([address], debug=0)
            mcservers[address] = mc
        else:
            mc = mcservers[address]
 
        item = mc.get(str(match['id'])).strip()
        item = unicode(item, 'gb18030', 'ignore').encode('utf-8', 'ignore')
        for words in result['words']:
            #print words['word'], "\033[31m%s" % words['word'], words['word']
            if debug > 1:
                item = item.replace(words['word'], '\033[32;49;1m%s\033[32;49;0m' % words['word'])
            elif debug < 1:
                item = item.replace(words['word'], '<b>%s</b>' % words['word'])

        li = parse_item(item)
        if debug:
            print '\t'.join(li)

        if li:
            r['result'] += 1
            r['matches'].append(li)

    cl.Close()
    
    return r

if __name__ == '__main__':
    import sys

    if len(sys.argv) < 2:
        print "Usage: %s queryexp oquery query debuglevel" % sys.argv[0]
        sys.exit()

    queryexp = sys.argv[1]
    oquery = sys.argv[2]
    query = sys.argv[3]
    debuglevel = int(sys.argv[4])

    result = search_sessiondata(queryexp, oquery, query, debuglevel)
    #print result
